package in.animeshpathak.saferstreets;

import in.animeshpathak.saferstreets.models.IncidentReport;
import in.animeshpathak.saferstreets.models.PMF;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.*;

import org.apache.velocity.VelocityContext;

@SuppressWarnings("serial")
public class QueryServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		/*  create a context and add data */

		PersistenceManager pm = PMF.get().getPersistenceManager();

		Query query = pm.newQuery(IncidentReport.class);
		query.setOrdering("timeStamp desc");

		List<IncidentReport> results;

		try {

			results = (List<IncidentReport>) query.execute();
		} finally {
			query.closeAll();
		}

		StringBuilder pagehtmlbuilder = new StringBuilder();

		String fileType = req.getParameter("type");
		if(fileType != null && fileType.equalsIgnoreCase("json")){
			resp.setContentType("application/json");
			//open JSON array
			pagehtmlbuilder.append("{"+"\""+"position"+"\""+":[");//start
			for(IncidentReport r : results){
				pagehtmlbuilder.append("{"+"\""+"type"+"\""+":\""+r.getIncidentType() +"\""+", "+"\""+"lat"+"\""+":"+r.getLatitude()+", "+"\"" +"long"+"\""+":"+
						r.getLongitude() +", "+ "\""+"time"+"\""+":"+"\"" + r.getTimeStamp()+"\""+", "+"\""+"key"+"\""+":"+"\""+ r.getKey().getId() +"\"},");
			}
			if(pagehtmlbuilder.length() > 1)
				pagehtmlbuilder.deleteCharAt(pagehtmlbuilder.length() - 1 ); //remove trailing comma
			pagehtmlbuilder.append("]}");//end
			resp.getWriter().write(pagehtmlbuilder.toString());
			resp.flushBuffer();

		} else {
			//return HTML
			pagehtmlbuilder.append(results.size() + " results found<br/>\n<ul class=\"incidentreports\">");

			for(IncidentReport r : results){
				pagehtmlbuilder.append("<li>"+r.getIncidentType() +" at ("+r.getLatitude()+", " +
						r.getLongitude() +") @ " + r.getTimeStamp()+
						(r.getShowId() ? " by "+ r.getReporter().getNickname() : "") +
						"</li>");
			}
			pagehtmlbuilder.append("</ul>");

			VelocityContext context = new VelocityContext();
			context.put("page_html",pagehtmlbuilder.toString());
			Utils.renderTemplate("res/queryresult.html", resp, context);	}
	}
}